﻿using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using yafc.Activity;
using yafc.Interface;
using yafc.UI;
using yafc.UI.Components;

namespace yafc.UI
{
    public partial class Mainframe : Form
	{
		#region Fields

		private SessionView sv = new SessionView("default");

		private ManualResetEvent signalExit = new ManualResetEvent(false);

		#endregion

		#region Constructor
		public Mainframe()
        {
            InitializeComponent();

			sessionPanel.Controls.Add(sv);
			sv.Dock = DockStyle.Fill;
        }
		#endregion

		#region Public Methods


		#endregion

		#region Private Methods

		#region Plugin

		// TODO: put this to about box.
		private string PluginInfo
		{
			get
			{
				string info = "Plugins:" + Environment.NewLine;
				foreach (IPlugin p in Plugin.Values())
				{
					info += Environment.NewLine + p.Name + ": " + p.Desc;
				}
				return info;
			}
		}

		private void checkPlugins(string Path)
		{
			string[] paths = Directory.GetFiles(Path, "*.dll");
			foreach (string path in paths)
			{
				if (path.Substring(path.LastIndexOf(".")) == ".dll")
				{
					try
					{
						string file = path.Substring(path.LastIndexOf("\\") + 1);
						Assembly asm = Assembly.LoadFile(path);
						Type[] types = asm.GetTypes();

						foreach (Type type in types)
						{
							if (!type.IsInterface
								&& type.GetInterface("yafc.Interface.IPlugin", true) == typeof(Interface.IPlugin))
							{
								IPlugin plugin = (IPlugin)asm.CreateInstance(type.FullName);
								Plugin.Add(plugin);
							}
						}
					}
					catch (System.Exception ex)
					{
						MessageBox.Show(ex.Message, "Load Plugin Failed", MessageBoxButtons.OK);
					}
				}
			}
		}

		private void buildPluginsMenu()
		{
			foreach(IPlugin p in Plugin.Values())
			{
				ToolStripMenuItem item = new ToolStripMenuItem(p.Name);
				item.Click += onMenuClick;
				serviceToolStripMenuItem.DropDownItems.Add(item);
			}
		}

		#endregion 
		
		private void mainframe_Load(object sender, EventArgs e)
		{
			checkPlugins(Application.StartupPath);
			buildPluginsMenu();
		}

		private void onMenuClick(object sender, EventArgs e)
		{
			ToolStripItem item = (ToolStripItem)sender;

			IPlugin p;
			if (Plugin.TryGet(item.Text, out p))
			{
				sv.Login(p);
			}
		}

		private void helpMenuItemAbout_Click(object sender, EventArgs e)
		{
			About about = new About();
			about.Description += PluginInfo;
			about.ShowDialog();
		}

		private void helpMenuItemHelp_Click(object sender, EventArgs e)
		{
			HelpInfo helpInfo = new HelpInfo();
			helpInfo.ShowDialog();
		}

		#endregion

		private void Mainframe_Activated(object sender, EventArgs e)
		{
			sv.Focus();
		}
	}
}
